package cn.turboinfo.dongying.api.gateway.admin.framework.http.interceptor;

import cn.turboinfo.dongying.api.gateway.web.framework.http.interceptor.BaseHandlerInterceptorAdapter;
import cn.turboinfo.dongying.api.gateway.admin.framework.http.context.AdminRequestContext;
import cn.turboinfo.dongying.api.gateway.admin.framework.http.context.AdminRequestContextHolder;
import cn.turboinfo.dongying.api.gateway.web.framework.http.interceptor.BaseHandlerInterceptorAdapter;
import cn.turboinfo.dongying.api.provider.admin.component.session.AdminSessionHelper;
import cn.turboinfo.dongying.api.provider.admin.framework.shiro.session.AdminSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@RequiredArgsConstructor
@Component
public class AdminRequestContextInterceptor extends BaseHandlerInterceptorAdapter {

    private final AdminSessionHelper sessionHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("收到请求: {}", request.getRequestURI());

        String referer = request.getHeader("referer");
//        if (StringUtils.isBlank(referer) || (!"https://www.fydzsw.cn/".equals(referer))) {
//            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED, "未授权");
//            return false;
//        }

        AdminRequestContextHolder.reset();

        // 验证并续期会话
        AdminSession session = sessionHelper.getSession();
        if (session != null) {
            // 保存信息到 context
            AdminRequestContext requestContext = AdminRequestContextHolder.current();
            requestContext.setUserId(session.getSysUserId());
            requestContext.setSession(session);
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
        AdminRequestContextHolder.reset();
        log.debug("结束请求: {}", request.getRequestURI());
    }

}
